package com.jokerpan.project.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jokerpan.project.commons.PaginationBuilder;
import com.jokerpan.project.entity.BackFiles;
import com.jokerpan.project.entity.Users;
import com.jokerpan.project.mapper.UsersMapper;
import com.jokerpan.project.service.*;
import com.jokerpan.project.util.ContextHolderUtils;
import com.jokerpan.project.util.JwtUtils;
import com.jokerpan.project.util.UserTool;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author jokerpan
 */
@Service("usersService")
public class UsersServiceImpl implements UsersService, UserDetailsService {

    @Resource
    UsersMapper usersMapper;
    @Resource
    BackFilesService backFilesService;
    @Resource
    MinIoService minIoService;
    @Resource
    UserTool userTool;


    @Override
    public Map<String, Object> queryList(Users users) {
        Page<Object> page = PageHelper.startPage(users.getCurrentPage(), users.getPageSize());
        List<Users> resultList = this.usersMapper.queryList(users);
        return PaginationBuilder.buildResult(resultList, page.getTotal(), users.getCurrentPage(), users.getPageSize());
    }

    @Override
    public Users queryById(Integer id) {
        return usersMapper.queryById(id);
    }

    @Override
    public Users checkLoginName(String loginName) {
        return usersMapper.checkLoginName(loginName);
    }

    @Override
    public BackFiles queryAvatar(BackFiles backFiles) {
        return usersMapper.queryAvatar(backFiles);
    }

    @Override
    public Boolean add(Users users) {
        return usersMapper.add(users) > 0;
    }

    @Override
    public Boolean update(Users users) {
        boolean flag = usersMapper.update(users) > 0;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))){
            return flag;
        }
        //修改完用户信息后刷新redis
        userTool.refreshRedis();
        return flag;
    }

    @Override
    public Boolean deleteById(Integer id) {
        Users users = usersMapper.queryById(id);
        BackFiles backFiles = new BackFiles();
        backFiles.setSource("USERS");
        backFiles.setPk(id);
        boolean aFlag = true, bFlag=true;
        //判断用户头像是否为默认头像[默认头像不做任何操作]
        if (users.getAvatar().indexOf("jokerpan-bucket") > -1){
            aFlag = backFilesService.deleteBySourceAndPk(backFiles);
            bFlag = minIoService.deleteFile(users.getAvatar());
        }
        return usersMapper.deleteById(id) > 0 && aFlag && bFlag;
    }

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        Users users = usersMapper.checkLoginName(loginName);
        if (users == null){
            throw new UsernameNotFoundException("用户名错误！！");
        }
        //获取用户权限，并把其添加到GrantedAuthority中
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        GrantedAuthority grantedAuthority=new SimpleGrantedAuthority(users.getRoleName());
        grantedAuthorities.add(grantedAuthority);
        String permissions[] = users.getPermissionList().split(",");
        for (int i = 0; i < permissions.length; i++){
            grantedAuthorities.add(new SimpleGrantedAuthority(permissions[i]));
        }
        return new org.springframework.security.core.userdetails.User(loginName,users.getPassword(),
                users.isEnabled(), users.isAccountNonExpired(), users.isCredentialsNonExpired(),
                users.isAccountNonLocked()
                ,grantedAuthorities);
    }

    /**
     * 用户登入成功默认所有角色权限
     * @return
     */
    private List<GrantedAuthority> getGrantedAuthority() {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("all"));
        return authorities;
    }
}